package com.vdong.restful.task;

import com.vdong.data.model.TrafficStatistics;
import com.vdong.data.service.TrafficStatisticsService;
import com.vdong.redisutil.distributionredis.service.SequenceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Set;


/**
 * 流量统计定时任务
 */
@Component
public class CounterTask {
    private Logger logger = LoggerFactory.getLogger(CounterTask.class);
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SequenceService sequenceService;

    @Autowired
    private TrafficStatisticsService trafficStatisticsService;
    @Value("${counter.task.switch}")
    private String CounterTaskSwitch;

    /**
     * 每小时统计一次，为0的删除key，大于0的置空并保存（原子）
     */
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void taskRun() {
        if (CounterTaskSwitch != null && CounterTaskSwitch.equals("true")) {
            logger.info("CounterTask:run:" + LocalDateTime.now());
            Set<String> keys = stringRedisTemplate.keys("counter|*");
            Set<String> keysException = stringRedisTemplate.keys("counter_exception|*");
            saveKyes(keys, 0);
            saveKyes(keysException, 1);
        }


    }

    public void saveKyes(Set<String> keys, int type) {
        long num = 0;
        String[] value;
        for (String str : keys) {
            num = sequenceService.generateZero(str);
            if (num == 0) {
                stringRedisTemplate.delete(str);
            } else if (num > 0) {

                value = str.split("\\|");
                TrafficStatistics trafficStatistics = new TrafficStatistics();
                trafficStatistics.setAppid(value[2]);
                trafficStatistics.setCreateTime(LocalDateTime.now());
                trafficStatistics.setNum(num);
                trafficStatistics.setType(0);
                trafficStatistics.setRestfulInterfaceId(value[1]);
                trafficStatisticsService.save(trafficStatistics);
            }


        }
    }
}
